//
//  MOHTMLLoadViewController.m
//  MobileOffice
//
//  Created by 冰冰 on 2019/6/24.
//  Copyright © 2019 com.idolmedia. All rights reserved.
//

#import "MOHTMLLoadViewController.h"
#import "MOWaitDoDetail_DoingModel.h"
#import "MOOfficeTextSearchModel.h"

@interface MOHTMLLoadViewController ()<UIWebViewDelegate>

@property(nonatomic,strong)UIWebView *webView;

@property(nonatomic,strong)UILabel *contentLabel;

@end


@implementation MOHTMLLoadViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"文件详情";
    
    [self.view addSubview:self.webView];

    
    [self getData];
}

-(BOOL)isNeedForStr:(NSString *)str
{
    NSString *postfix = [str pathExtension];//[str componentsSeparatedByString:@"."][1];
    if ([postfix isEqualToString:@"pdf"]||[postfix isEqualToString:@"doc"]||[postfix isEqualToString:@"docx"]||[postfix isEqualToString:@"xls"]||[postfix isEqualToString:@"xlsx"]) {
        return YES;
    }else{
        return NO;
    }
}

-(void)getData
{
    /*
     从哪个页面来
     1.待办正文
     2.待办附件
     3.已办正文
     4.已办附件
     5.查询正文
     6.查询附件
     7.局内
     */
    
    if ([self.comeType integerValue]==1||[self.comeType integerValue]==3) {//待办 已办正文
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [PPNetworkHelper GET:self.urlStr parameters:@{} success:^(id responseObject) {
//            NSLog(@"webHtml：%@",responseObject);
            //        [MBProgressHUD hideHUDForView:self.view animated:YES];
            if ([responseObject[@"status"] integerValue]==1) {
                
                NSString *contentStr = [NSString passNullForString:responseObject[@"content"]];
                
                if ([contentStr rangeOfString:@"{margin:"].location!=NSNotFound) {
                    NSInteger location1 = [[NSString passNullForString:responseObject[@"content"]] rangeOfString:@"{margin:"].location;
                    NSInteger location2 = [[NSString passNullForString:responseObject[@"content"]] rangeOfString:@"2em;}"].location;
                    NSString *str = [[NSString passNullForString:responseObject[@"content"]] substringWithRange:NSMakeRange(location1, location2 - location1 + 5)];
                    //上 右 下 左
                    contentStr = [contentStr stringByReplacingOccurrencesOfString:str withString:@"{margin: 1em 1em 1em 1em;}"];
                }
                [self.webView loadHTMLString:[self contentStr:contentStr] baseURL:nil];
                
            }else{
                [MBProgressHUD hideHUDForView:self.view animated:YES];
            }
            
        } failure:^(NSError *error) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            NSLog(@"webHtml）：%@",[error localizedDescription]);
        }];
    }else if ([self.comeType integerValue]==2||[self.comeType integerValue]==4){//待办  已办附件
        
        if (self.fileName.length>0&&[self isNeedForStr:self.fileName]==YES) {
            
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            NSString *url = [NSString stringWithFormat:@"%@/%@?filepath=%@&filename=%@&authorization=%@",ODPSDB_ODPSWATCHDOCUMENTSU_URL,self.domain,self.filePath,self.fileName,[NSString URLEncodedString:[MOUser sharedMOUser].token]];
            
            [PPNetworkHelper GET:url parameters:@{} success:^(id responseObject) {
                
                if ([responseObject[@"status"] integerValue]==1) {
                    NSString *contentStr = [NSString passNullForString:responseObject[@"content"]];
                    
                    [self.webView loadHTMLString:[self contentStr:contentStr] baseURL:nil];
                    
                }else{
                    [MBProgressHUD hideHUDForView:self.view animated:YES];
                    [[ADShowMessage shareShowMessage]showTextOnly:@"加载失败" showInView:self.view];
                }
                
            } failure:^(NSError *error) {
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                [[ADShowMessage shareShowMessage]showTextOnly:[error localizedDescription] showInView:self.view];
                
            }];
            
//            [PPNetworkHelper downloadWithURL:url fileDir:@"" progress:^(NSProgress *progress) {
//                [MBProgressHUD hideHUDForView:self.view animated:YES];
//            } success:^(NSString *filePath) {
//
//                NSInteger location = [filePath rangeOfString:@".doc"].location+4;
//                filePath = [filePath substringToIndex:location];
//                filePath = [filePath stringByReplacingOccurrencesOfString:@"file:///" withString:@""];
//
//                [MBProgressHUD hideHUDForView:self.view animated:YES];
//                NSURL *url = [NSURL fileURLWithPath:filePath];
//                NSURLRequest *request = [NSURLRequest requestWithURL:url];
//                [self.webView loadRequest:request];
//                [self.webView setScalesPageToFit:YES];
//            } failure:^(NSError *error) {
//                [MBProgressHUD hideHUDForView:self.view animated:YES];
//            }];
            
        }else{
            
            //ODPSDB_ODPSWATCHDOCUMENT_URL
            self.urlStr = [NSString stringWithFormat:@"%@/%@?filepath=%@&filename=%@&authorization=%@",ODPSDB_ODPSWATCHDOCUMENTSU_URL,self.domain,self.filePath,self.fileName,[NSString URLEncodedString:[MOUser sharedMOUser].token]];
            
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            [PPNetworkHelper GET:self.urlStr parameters:@{} success:^(id responseObject) {
                //        [MBProgressHUD hideHUDForView:self.view animated:YES];
                if ([responseObject[@"status"] integerValue]==1) {
                    
                    [self.webView loadHTMLString:[self contentStr:[NSString passNullForString:responseObject[@"content"]]] baseURL:nil];
                    
                }else{
                    [MBProgressHUD hideHUDForView:self.view animated:YES];
                }
                
            } failure:^(NSError *error) {
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                NSLog(@"webHtml）：%@",[error localizedDescription]);
            }];
        }
    }else if ([self.comeType integerValue]==5){//查询正文
    
        MOOfficeTextSearchModel *model1 = self.searchConditionArray[0][0];
        MOOfficeTextSearchModel *model2 = self.searchConditionArray[1][0];
        MOOfficeTextSearchModel *model3 = self.searchConditionArray[1][1];
        MOOfficeTextSearchModel *model4 = self.searchConditionArray[1][2];
        MOOfficeTextSearchModel *model5 = self.searchConditionArray[2][0];
        MOOfficeTextSearchModel *model6 = self.searchConditionArray[3][0];

        NSString *url = [NSString stringWithFormat:@"%@?authorization=%@",ODPSCX_WJZHCXQUERYWJCONTENT_URL,[NSString URLEncodedString:[MOUser sharedMOUser].token]];

        NSDictionary *par = @{
                              @"bt":model1.valueStr?model1.valueStr:@"",
                              @"wjz":model2.valueStr?model2.valueStr:@"",
                              @"wjnf":model3.valueStr?model3.valueStr:@"",
                              @"wjh":model4.valueStr?model4.valueStr:@"",
                              @"wjlx":model5.valueStr?model5.valueStr:@"",
                              @"zbbmmc":model6.valueStr?model6.valueStr:@"",
                              @"wjKey":self.key
                              };
        
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [PPNetworkHelper POST:url parameters:par success:^(id responseObject) {
//            NSLog(@"公文查询：%@",responseObject);
            
            NSString *contentStr = [NSString passNullForString:responseObject[@"content"]];
            
            if ([contentStr rangeOfString:@"{margin:"].location!=NSNotFound && [contentStr rangeOfString:@"2em;}"].location!=NSNotFound) {
                NSInteger location1 = [[NSString passNullForString:responseObject[@"content"]] rangeOfString:@"{margin:"].location;
                NSInteger location2 = [[NSString passNullForString:responseObject[@"content"]] rangeOfString:@"2em;}"].location;
                NSString *str = [[NSString passNullForString:responseObject[@"content"]] substringWithRange:NSMakeRange(location1, location2 - location1 + 5)];
                //上 右 下 左
                contentStr = [contentStr stringByReplacingOccurrencesOfString:str withString:@"{margin: 1em 1em 1em 1em;}"];
            }else if ([contentStr rangeOfString:@"{margin:"].location!=NSNotFound && [contentStr rangeOfString:@"in;}"].location!=NSNotFound){
                
                NSInteger location1 = [[NSString passNullForString:responseObject[@"content"]] rangeOfString:@"{margin:"].location;
                NSInteger location2 = [[NSString passNullForString:responseObject[@"content"]] rangeOfString:@"in;}"].location;
                NSString *str = [[NSString passNullForString:responseObject[@"content"]] substringWithRange:NSMakeRange(location1, location2 - location1 + 5)];
                //上 右 下 左
                contentStr = [contentStr stringByReplacingOccurrencesOfString:str withString:@"{margin: 1em 1em 1em 1em;}"];
                
            }
            
            [self.webView loadHTMLString:[self contentStr:contentStr] baseURL:nil];
            
        } failure:^(NSError *error) {
            NSLog(@"公文查询：%@",[error localizedDescription]);
            [[ADShowMessage shareShowMessage]showTextOnly:[error localizedDescription] showInView:self.view];
        }];
        
        
    }else if ([self.comeType integerValue]==6){//查询附件
        
        if (self.fileName.length>0&&[self isNeedForStr:self.fileName]==YES) {
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            NSString *url = [NSString stringWithFormat:@"%@/%@?filepath=%@&filename=%@&authorization=%@",ODPSDB_ODPSWATCHDOCUMENTSU_URL,self.domain,self.filePath,self.fileName,[NSString URLEncodedString:[MOUser sharedMOUser].token]];
            
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            [PPNetworkHelper GET:url parameters:@{} success:^(id responseObject) {
                //        [MBProgressHUD hideHUDForView:self.view animated:YES];
                if ([responseObject[@"status"] integerValue]==1) {
                    
                    [self.webView loadHTMLString:[self contentStr:[NSString passNullForString:responseObject[@"content"]]] baseURL:nil];
                    
                }else{
                    [[ADShowMessage shareShowMessage]showTextOnly:@"加载失败" showInView:self.view];
                    [MBProgressHUD hideHUDForView:self.view animated:YES];
                }
                
            } failure:^(NSError *error) {
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                NSLog(@"webHtml）：%@",[error localizedDescription]);
            }];
            
            
//            [PPNetworkHelper downloadWithURL:url fileDir:@"" progress:^(NSProgress *progress) {
//                [MBProgressHUD hideHUDForView:self.view animated:YES];
//            } success:^(NSString *filePath) {
//
//                NSInteger location = [filePath rangeOfString:@".pdf"].location+4;
//                filePath = [filePath substringToIndex:location];
//                filePath = [filePath stringByReplacingOccurrencesOfString:@"file:///" withString:@""];
//
//                [MBProgressHUD hideHUDForView:self.view animated:YES];
//                NSURL *url = [NSURL fileURLWithPath:filePath];
//                NSURLRequest *request = [NSURLRequest requestWithURL:url];
//                [self.webView loadRequest:request];
//                [self.webView setScalesPageToFit:YES];
//            } failure:^(NSError *error) {
//                [MBProgressHUD hideHUDForView:self.view animated:YES];
//            }];
        }else{
            
            NSString *url = [NSString stringWithFormat:@"%@/%@?filepath=%@&filename=%@&authorization=%@",ODPSDB_ODPSWATCHDOCUMENTSU_URL,self.domain,self.filePath,self.fileName,[NSString URLEncodedString:[MOUser sharedMOUser].token]];
            NSDictionary *par = @{};
            
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            [PPNetworkHelper POST:url parameters:par success:^(id responseObject) {
//                NSLog(@"公文查询：%@",responseObject);
                
                NSString *contentStr = [NSString passNullForString:responseObject[@"content"]];
                
                if ([contentStr rangeOfString:@"{margin:"].location!=NSNotFound) {
                    NSInteger location1 = [[NSString passNullForString:responseObject[@"content"]] rangeOfString:@"{margin:"].location;
                    NSInteger location2 = [[NSString passNullForString:responseObject[@"content"]] rangeOfString:@"2em;}"].location;
                    NSString *str = [[NSString passNullForString:responseObject[@"content"]] substringWithRange:NSMakeRange(location1, location2 - location1 + 5)];
                    //上 右 下 左
                    contentStr = [contentStr stringByReplacingOccurrencesOfString:str withString:@"{margin: 1em 1em 1em 1em;}"];
                }
                
                [self.webView loadHTMLString:[self contentStr:contentStr] baseURL:nil];
                
            } failure:^(NSError *error) {
                NSLog(@"公文查询：%@",[error localizedDescription]);
                [[ADShowMessage shareShowMessage]showTextOnly:[error localizedDescription] showInView:self.view];
            }];
        }
        
    }else if ([self.comeType integerValue]==7){//局内
        
        if (self.fileName.length>0&&[self isNeedForStr:self.fileName]==YES) {
            
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            NSString *url = [NSString stringWithFormat:@"%@/%@?filepath=%@&filename=%@&authorization=%@",ODPSDB_ODPSWATCHDOCUMENTSU_URL,self.domain,self.filePath,self.fileName,[NSString URLEncodedString:[MOUser sharedMOUser].token]];
            
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            [PPNetworkHelper GET:url parameters:@{} success:^(id responseObject) {
                //        [MBProgressHUD hideHUDForView:self.view animated:YES];
                if ([responseObject[@"status"] integerValue]==1) {
                    
                    [self.webView loadHTMLString:[self contentStr:[NSString passNullForString:responseObject[@"content"]]] baseURL:nil];
                    
                }else{
                    [[ADShowMessage shareShowMessage]showTextOnly:@"加载失败" showInView:self.view];
                    [MBProgressHUD hideHUDForView:self.view animated:YES];
                }
                
            } failure:^(NSError *error) {
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                NSLog(@"webHtml）：%@",[error localizedDescription]);
            }];
            
//            [PPNetworkHelper downloadWithURL:url fileDir:@"" progress:^(NSProgress *progress) {
//                 [MBProgressHUD hideHUDForView:self.view animated:YES];
//            } success:^(NSString *filePath) {
//
//                NSInteger location = [filePath rangeOfString:@".pdf"].location+4;
//                filePath = [filePath substringToIndex:location];
//                filePath = [filePath stringByReplacingOccurrencesOfString:@"file:///" withString:@""];
//
//                 [MBProgressHUD hideHUDForView:self.view animated:YES];
//                NSURL *url = [NSURL fileURLWithPath:filePath];
//                NSURLRequest *request = [NSURLRequest requestWithURL:url];
//                [self.webView loadRequest:request];
//                [self.webView setScalesPageToFit:YES];
//            } failure:^(NSError *error) {
//                 [MBProgressHUD hideHUDForView:self.view animated:YES];
//            }];

        }else{
            NSString *url = [NSString stringWithFormat:@"%@?authorization=%@",JNFB_GETJNFBFJCONTENT_URL,[NSString URLEncodedString:[MOUser sharedMOUser].token]];
            NSDictionary *par = @{
                                  @"wjKey":self.key,
                                  @"fileName":self.fileName
                                  };
            
            NSError *parseError = nil;
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:par options:NSJSONWritingPrettyPrinted error:&parseError];
            NSString *param = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            [PPNetworkHelper POST:url parameters:@{@"param":param} success:^(id responseObject) {
//                NSLog(@"局内发布获取附件：%@",responseObject);
                
                if ([responseObject[@"status"] integerValue]==1) {
                    
                    NSString *contentStr = [NSString passNullForString:responseObject[@"content"]];
                    
                    if ([contentStr rangeOfString:@"{margin:"].location!=NSNotFound) {
                        NSInteger location1 = [[NSString passNullForString:responseObject[@"content"]] rangeOfString:@"{margin:"].location;
                        NSInteger location2 = [[NSString passNullForString:responseObject[@"content"]] rangeOfString:@"2em;}"].location;
                        NSString *str = [[NSString passNullForString:responseObject[@"content"]] substringWithRange:NSMakeRange(location1, location2 - location1 + 5)];
                        //上 右 下 左
                        contentStr = [contentStr stringByReplacingOccurrencesOfString:str withString:@"{margin: 1em 1em 1em 1em;}"];
                    }
                    
                    
                    [self.webView loadHTMLString:[self contentStr:contentStr] baseURL:nil];
                    
                }else{
                    [MBProgressHUD hideHUDForView:self.view animated:YES];
                }
                
            } failure:^(NSError *error) {
                NSLog(@"局内发布获取附件：%@",[error localizedDescription]);
                [[ADShowMessage shareShowMessage]showTextOnly:[error localizedDescription] showInView:self.view];
            }];
        }
    }
}


-(NSString *)contentStr:(NSString *)contentStr
{
    NSString *htmls = [NSString stringWithFormat:@"<html> \n"
                       "<head> \n"
                       "<meta name=\"viewport\" content=\"initial-scale=1.0, maximum-scale=1.0, user-scalable=no\" /> \n"
                       "<style type=\"text/css\"> \n"
                       "body {font-size:15px;}\n"
                       "</style> \n"
                       "</head> \n"
                       "<body>"
                       "<script type='text/javascript'>"
                       "window.onload = function(){\n"
                       "var $img = document.getElementsByTagName('img');\n"
                       "for(var p in  $img){\n"
                       " $img[p].style.width = '100%%';\n"
                       "$img[p].style.height ='auto'\n"
                       "}\n"
                       "}"
                       "</script>%@"
                       "</body>"
                       "</html>",contentStr];
//    NSLog(@"%@",htmls);
    return htmls;
}

-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    
    [_webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];
    
    NSString *meta = [NSString stringWithFormat:@"var meta = document.createElement('meta');meta.content='width=device-width,initial-scale=1.0,minimum-scale=.5,maximum-scale=3';meta.name='viewport';document.getElementsByTagName('head')[0].appendChild(meta);"];
    [webView stringByEvaluatingJavaScriptFromString:meta];
}


-(UIWebView *)webView
{
    if (!_webView) {// + kWConversions(80)
        _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        _webView.backgroundColor = [UIColor whiteColor];
        _webView.delegate = self;
        _webView.opaque = NO;
        _webView.scrollView.showsHorizontalScrollIndicator = NO;
//        _webView.scrollView.showsVerticalScrollIndicator = NO;
        _webView.scrollView.decelerationRate=UIScrollViewDecelerationRateNormal;
        
        _webView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
        _webView.scalesPageToFit=YES;
        _webView.multipleTouchEnabled=YES;
        _webView.userInteractionEnabled=YES;
        
    }
    return _webView;
}




@end
